import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    Card, Button, Typography, Spin, Empty, Layout, Space,
    Form, Input, Modal
} from 'antd';
import { ArrowLeftOutlined, EditOutlined } from '@ant-design/icons';
import { ArticleModel } from "./ArticleModel";
import {api} from "./api/request";

const { Content } = Layout;
const { Title, Paragraph } = Typography;
const { TextArea } = Input;

const ArticleDetail = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const [article, setArticle] = useState<ArticleModel | null>(null);
    const [loading, setLoading] = useState(true);
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
    const [form] = Form.useForm();

    // 加载文章详情
    const fetchArticleDetail = async () => {
        setLoading(true);
        try {
            const response = await api.get(`article/get/${id}`);
            setArticle(response.data);
            // 初始化表单数据
            form.setFieldsValue({
                id: response.data.id,
                title: response.data.articleName,
                author: response.data.author,
                content: response.data.content
            });
        } catch (error) {
            console.error('获取文章详情失败:', error);
            setArticle(null);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchArticleDetail().then();
    }, [id, form]);

    // 返回列表页
    const handleBack = () => {
        navigate('/blogs/page');
    };

    // 显示编辑弹窗
    const handleEdit = () => {
        setIsEditModalVisible(true);
    };

    // 提交编辑表单
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            // 调用createOrUpdateBlog接口
            await api.post('blogs/create-or-update', values);
            // 关闭弹窗并刷新文章详情
            setIsEditModalVisible(false);
            fetchArticleDetail();
        } catch (error) {
            console.error('提交失败:', error);
        }
    };

    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Content style={{ padding: '0 50px', marginTop: 20 }}>
                <Space style={{ marginBottom: 16 }}>
                    <Button
                        type="primary"
                        icon={<ArrowLeftOutlined />}
                        onClick={handleBack}
                    >
                        返回列表页
                    </Button>

                    {/* 编辑按钮 - 新增部分 */}
                    {article && (
                        <Button
                            type="default"
                            icon={<EditOutlined />}
                            onClick={handleEdit}
                        >
                            编辑文章
                        </Button>
                    )}
                </Space>

                <Spin spinning={loading} tip="加载中...">
                    {article ? (
                        <Card title={<Title level={3}>文章详情</Title>} bordered={false}>
                            <Typography>
                                <Title level={4}>文章 ID：{article.id}</Title>
                                <Title level={4}>文章标题：{article.articleName}</Title>
                                <Title level={4}>创建时间：{article.createTime}</Title>
                                <Title level={4}>更新时间：{article.updateTime}</Title>
                                <Title level={4}>作者：{article.author}</Title>
                                <Title level={4} style={{ marginTop: 20 }}>文章内容</Title>
                                <Paragraph style={{ fontSize: 16, lineHeight: 2 }}>
                                    {article.content}
                                </Paragraph>
                            </Typography>
                        </Card>
                    ) : (
                        !loading && <Empty description="文章不存在或加载失败" />
                    )}
                </Spin>

                {/* 编辑弹窗 - 新增部分 */}
                <Modal
                    title="编辑文章"
                    open={isEditModalVisible}
                    onCancel={() => setIsEditModalVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setIsEditModalVisible(false)}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleSubmit}>
                            保存
                        </Button>,
                    ]}
                    destroyOnClose={true}
                    width={700}
                >
                    <Form
                        form={form}
                        layout="vertical"
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            name="id"
                            hidden // ID字段隐藏，用于后端识别是更新操作
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="title"
                            label="文章标题"
                            rules={[{ required: true, message: '请输入文章标题' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="author"
                            label="作者"
                            rules={[{ required: true, message: '请输入作者' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="content"
                            label="文章内容"
                            rules={[{ required: true, message: '请输入文章内容' }]}
                        >
                            <TextArea rows={10} />
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
};

export default ArticleDetail;